package cn.moukou.tongji.ihealth.predication.websocket;

import cn.moukou.tongji.ihealth.predication.config.NettyConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;

public class WsHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    protected void channelRead0(ChannelHandlerContext ctx,
                                TextWebSocketFrame textWebSocketFrame) throws Exception {
        String uid = textWebSocketFrame.text();
        NettyConfig.getUserChannelMap().put(uid, ctx.channel());

        ctx.channel().writeAndFlush(new TextWebSocketFrame(uid));

        AttributeKey<String> key = AttributeKey.valueOf("uid");
        ctx.channel().attr(key).setIfAbsent(uid);

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.getChannelGroup().add(ctx.channel());
//        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
    }

    private void removeUserId(ChannelHandlerContext ctx){
        AttributeKey<String> key = AttributeKey.valueOf("uid");
        String uid = ctx.channel().attr(key).get();
        NettyConfig.getUserChannelMap().remove(uid);
    }
}
